package zut.edu.cs.network.io.data;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import zut.edu.cs.network.io.Person;

public class DateStreamDemo {
	static Person[] persons = new Person[] {new Person("sweet", 18),new Person("xiaoming", 19),new Person("xiaohong", 20)};

	public static void main(String[] args) {
		writeData();
		readData();
	}
	
	public static void writeData() {
		FileOutputStream file1;
		
		try {
			file1 = new FileOutputStream("persons.txt");
			DataOutputStream dos = new DataOutputStream(file1);
			for (Person person : persons) {
				dos.writeUTF(person.name);
				dos.writeChars(" ");
				dos.writeInt(person.age);
			}
			
			dos.close();
			file1.close();
			System.out.println("写入对象数组成功！");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void readData() {
		try {
			FileInputStream file = new FileInputStream("persons.txt");
			DataInputStream dis = new DataInputStream(file);
			
			Person[] person1 = new Person[persons.length];
			for (int i = 0; i < person1.length; i++) {
				String name = dis.readUTF();
				dis.readChar();
				int age = dis.readInt();
				
				Person p = new Person(name, age);
				person1[i] = p;
			}
			for (Person person : person1) {
				System.out.println(person);
			}
			dis.close();
			file.close();
			System.out.println("读取成功");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
